<template>
  <div class="cattle-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>奶牛档案管理</span>
          <div>
            <el-button
              v-if="userStore.isAdmin"
              type="success"
              :icon="Upload"
              @click="handleImport"
            >
              批量导入
            </el-button>
            <el-button
              v-if="userStore.isAdmin"
              type="warning"
              :icon="Download"
              @click="handleExport"
            >
              批量导出
            </el-button>
            <el-button
              type="primary"
              :icon="Plus"
              @click="handleAdd"
            >
              新增档案
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form
        :inline="true"
        :model="searchForm"
        class="search-form"
      >
        <el-form-item label="编号">
          <el-input
            v-model="searchForm.number"
            placeholder="请输入奶牛编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="品种">
          <el-input
            v-model="searchForm.breed"
            placeholder="请输入品种"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 表格 -->
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="loading"
      >
        <el-table-column prop="id" label="编号" width="180" />
        <el-table-column prop="breed" label="品种" width="120" />
        <el-table-column prop="birthDate" label="出生日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.birthDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="healthStatus" label="健康状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.healthStatus === '健康' ? 'success' : 'danger'">
              {{ row.healthStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="milkYield" label="产奶量(kg)" width="120" />
        <el-table-column prop="lastMilkDate" label="最近产奶日期" width="120">
          <template #default="{ row }">
            {{ row.lastMilkDate ? formatDate(row.lastMilkDate) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="owner" label="负责人" width="100" v-if="userStore.isAdmin" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              v-if="userStore.isAdmin || row.owner === userStore.username"
              type="warning"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="userStore.isAdmin"
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        :disabled="isReadOnly"
      >
        <el-form-item label="品种" prop="breed">
          <el-input
            v-model="formData.breed"
            placeholder="请输入品种"
          />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker
            v-model="formData.birthDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="健康状态" prop="healthStatus">
          <el-select
            v-model="formData.healthStatus"
            placeholder="请选择健康状态"
            style="width: 100%"
          >
            <el-option label="恢复中" value="恢复中" />
            <el-option label="未知" value="未知" />
            <el-option label="生病" value="生病" />
            <el-option label="隔离" value="隔离" />
            <el-option label="健康" value="健康" />
          </el-select>
        </el-form-item>
        <el-form-item label="产奶量(kg)" prop="milkProduction">
          <el-input-number
            v-model="formData.milkYield"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="最近产奶日期" prop="lastMilkDate">
          <el-date-picker
            v-model="formData.lastMilkDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <template v-if="isReadOnly">
          <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
        </template>
        <template v-else>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </template>
      </template>
    </el-dialog>
    
    <!-- 导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="批量导入"
      width="500px"
    >
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :limit="1"
        accept=".xlsx,.xls"
        :on-change="handleFileChange"
        :file-list="fileList"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <template #tip>
          <div class="el-upload__tip">
            仅支持 .xlsx 和 .xls 格式文件
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleImportSubmit">导入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Upload, Download } from '@element-plus/icons-vue'
import {
  getCattleList,
  createCattle,
  updateCattle,
  deleteCattle,
  importCattle,
  exportCattle
} from '@/api/cattle'
import dayjs from 'dayjs'

const userStore = useUserStore()

const loading = ref(false)
const tableData = ref([])
const dialogVisible = ref(false)
const importDialogVisible = ref(false)
const formRef = ref(null)
const uploadRef = ref(null)
const fileList = ref([])

const searchForm = reactive({
  number: '',
  breed: ''
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const formData = reactive({
  id: null,
  number: '',
  breed: '',
  birthDate: '',
  healthStatus: '',
  milkYield: 0,
  lastMilkDate: '',
  remark: ''
})

const formRules = {
  number: [
    { required: true, message: '请输入编号', trigger: 'blur' }
  ],
  breed: [
    { required: true, message: '请输入品种', trigger: 'blur' }
  ],
  birthDate: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  healthStatus: [
    { required: true, message: '请选择健康状态', trigger: 'change' }
  ]
}

const isEdit = ref(false)
const isReadOnly = ref(false)
const dialogTitle = computed(() => {
  if (isReadOnly.value) return '查看档案'
  return isEdit.value ? '编辑档案' : '新增档案'
})

// 获取列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: pagination.page,
      pageSize: pagination.size,
      ...searchForm
    }
    const res = await getCattleList(params)
    tableData.value = res.data.records || []
    pagination.total = res.data.total || 0
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  searchForm.number = ''
  searchForm.breed = ''
  pagination.page = 1
  fetchData()
}

// 分页
const handleSizeChange = (val) => {
  pagination.size = val
  fetchData()
}

const handlePageChange = (val) => {
  pagination.page = val
  fetchData()
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  isReadOnly.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  isReadOnly.value = false
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  isEdit.value = false
  isReadOnly.value = true
  // 日期字段格式化，确保el-date-picker能正常显示
  Object.assign(formData, {
    ...row,
    birthDate: row.birthDate ? dayjs(row.birthDate).format('YYYY-MM-DD') : '',
    lastMilkDate: row.lastMilkDate ? dayjs(row.lastMilkDate).format('YYYY-MM-DD') : ''
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这条档案吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCattle(row.id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await updateCattle(formData.id, formData)
          ElMessage.success('更新成功')
        } else {
          await createCattle(formData)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  formData.id = null
  formData.number = ''
  formData.breed = ''
  formData.birthDate = ''
  formData.healthStatus = ''
  formData.milkProduction = 0
  formData.lastMilkingDate = ''
  formData.remark = ''
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleDialogClose = () => {
  resetForm()
  isReadOnly.value = false
}

// 导入
const handleImport = () => {
  importDialogVisible.value = true
  fileList.value = []
}

// 文件选择
const handleFileChange = (file) => {
  fileList.value = [file]
}

// 提交导入
const handleImportSubmit = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择文件')
    return
  }
  
  try {
    await importCattle(fileList.value[0].raw)
    ElMessage.success('导入成功')
    importDialogVisible.value = false
    fileList.value = []
    fetchData()
  } catch (error) {
    ElMessage.error('导入失败')
  }
}

// 导出
const handleExport = async () => {
  try {
    const res = await exportCattle(searchForm)
    const blob = new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `奶牛档案_${dayjs().format('YYYY-MM-DD')}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD')
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.cattle-container {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

